package com.uiotsoft.small.host.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.uiotsoft.small.host.entity.HostClient;
import lombok.Data;

@Data
public class HostBaseController {

    public String getHTCTopic(String sn, String model, String type){
        String tmp = "common/host/{}/{}/{}";
        return StrUtil.format(tmp,model,sn,type);
    }

    public String getHTATopic(String sn, String model, String type){
        String tmp = "app/host/{}/{}/{}";
        return StrUtil.format(tmp,model,sn,type);
    }

    public void publishToCloud(HostClient hostClient ,String model,String type, JSONObject data){
        String pubTopic = getHTCTopic(hostClient.getSn(),model,type);
        String pubMsg = getSendData(hostClient,data);
        hostClient.getMyMqttClient().hostPublish(pubTopic,pubMsg);
    }

    public void publishToApp(HostClient hostClient ,String model,String type, JSONObject data){
        String pubTopic = getHTATopic(hostClient.getSn(),model,type);
        String pubMsg = getSendData(hostClient,data);
        hostClient.getMyMqttClient().hostPublish(pubTopic,pubMsg);
    }

    public JSONObject getHeader(HostClient hostClient){
        String header = "{\"params\":{},\"identity\":\"\",\"msgId\":\"\",\"appkey\":\"\",\"version\":\"1.0\",\"isEncrypt\":\"true\",\"compression\":\"none\",\"clientType\":\"host\",\"userUnique\":\"\"}";
        JSONObject headerJson = JSONUtil.parseObj(header);
        headerJson.put("identity", hostClient.getSn());
        headerJson.put("appkey", hostClient.getMyMqttClient().getAppKey());
        long time = System.currentTimeMillis();
        headerJson.put("msgId",time+"");
        return headerJson;
    }

    public String getSendData(HostClient hostClient, JSONObject data){
        JSONObject sendData = new JSONObject();
        sendData.put("header",getHeader(hostClient));
        sendData.put("payload",data);
        return sendData.toString();
    }
}
